package operation;

import book.Book;
import book.BookList;

import java.util.Scanner;

// 删除图书
public class DelOperation implements IOperation {
    @Override
    public void work(BookList bookList) {
        System.out.println("删除图书");
        System.out.println("输入你要删除书籍的名字：");
        Scanner sc = new Scanner(System.in);
        String name  = sc.nextLine();
        // 寻找删除书籍
        int index = 0;// 用来存储删除元素的下标
        int i = 0;
        for (; i < bookList.getUsedSize(); i++) {
            Book book = bookList.getPos(i);
            if (name.equals(book.getName())){
                index = i;
                break;
            }
        }
        // 进行删除
        if (i< bookList.getUsedSize()){
            for (int j = 0; j < bookList.getUsedSize()-1; j++) {
//                bookList[j] = bookList[j+1] error 错误写法，现在的 bookList 是一个变量，不是数组
                Book book = bookList.getPos(j+1);
                bookList.setBook(j,book);
            }
            bookList.setBook(bookList.getUsedSize(), null);// 将最后一个重复的元素（引用），置为null.
            bookList.setUsedSize(bookList.getUsedSize()-1);// 删除了一个元素，元素个数减一。
            System.out.println("删除成功");
            return;
        }
        System.out.println("没有你要删除的书");
    }
}
